package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
//分类模块
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    //分类列表
    @Override
    public List<Category> findAll() {
        //掉用mapper
        return categoryMapper.findAll();
    }

    //新增分类
    @Override
    public void save(Category category) {
        //1.补全信息
        long id = IdUtil.getSnowflake(1, 1).nextId();
        category.setId(id);
        //category.setCreateTime(new Date());//todo 后期完善
        //category.setUpdateTime(new Date());
        //category.setCreateUser(1L);//todo 后期完善
        //category.setUpdateUser(1L);

        //调用mapper添加
        categoryMapper.save(category);

    }

    //修改代码
    @Override
    public void updateById(Category category) {
        //1.补全信息
        //category.setUpdateUser(1L);//todo 后期完善
        //category.setUpdateTime(new Date());

        //2.调用mapper
        categoryMapper.updateById(category);
    }


    //删除分类
    @Override
    public void deleteById(Long id) {
        //1.根据id查询菜品数量,判断
        long countDish = categoryMapper.counDishByCategoryId(id);
        if (countDish>0){
            throw new CustomException("该分类下有菜品不允许删除");
        }
        //2.根据id查询套餐数量判断
        long countSetmeal = categoryMapper.countSetmealByCategoryId(id);
        if (countSetmeal>0){
            throw new CustomException("该分类下有套餐不允许删除");
        }
        //3.根据id删除分类
        categoryMapper.deleteById(id);

    }

    //分类回显
    @Override
    public List<Category> findById(Integer type) {
        //构建条件
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType,type);//类型条件
        qw.orderByAsc(Category::getSort);//排序

        //调用mapper查询并返回
        return categoryMapper.selectList(qw);
    }

}
